package com.stray.crawl.worker.task;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.stray.crawl.Constants.ConfigKey;
import com.stray.crawl.BeanContext;
import com.stray.crawl.TaskContext;
import com.stray.crawl.supt.EventPublisher;
import com.stray.crawl.supt.FileStorage;
import com.stray.crawl.utils.IOUtils;
import com.stray.crawl.worker.HttpEnums;
import com.stray.crawl.worker.TaskStatus;

public class BinaryCrawlTask extends CrawlTask {

	private FileStorage storage = BeanContext.get(FileStorage.class);

	public BinaryCrawlTask(EventPublisher<CrawlTask, TaskStatus> publisher, TaskContext taskContext) {
		super(publisher, taskContext);
	}

	@Override
	protected Object convertContent(HttpEntity entity) throws IOException {
		return EntityUtils.toByteArray(entity);
	}

	@Override
	protected void doAction() throws IOException {
		URL url = taskContext.getUrl();
		String filename = HttpEnums.getFilename(url);
		filename = (filename == null || filename.length() == 0) ? UUID.randomUUID().toString() : filename;

		String path = storage.getResourcePath(filename, taskContext.getConfig(ConfigKey.STORAGE_PREFIX));
		byte[] data = (byte[]) resultContext.getContent();

		InputStream in = null;

		try {
			in = new ByteArrayInputStream(data);
			storage.storeToPath(path, in);
		} finally {
			IOUtils.closeQuietly(in);
		}
	}

}